import SendMsg from "@/api/SendMsg";
import {message} from "ant-design-vue";
import router from "@/router";
import i18n from "@/i18n";

const js3200 = {
    namespaced: true,
    state: {
        // table数据
        dataSource: [],

        loadTable: false,
        // 新增/编辑表单数据
        capForm: {
            name: '',
            desc: '',
        },
        // 新增/编辑弹窗是否可见
        capvisible: false,
        // 分配权限弹窗是否可见
        controlVisible: false,
        // 编辑弹窗状态
        isFlag: null,
        // 选中行
        selectRow: {},

        // 选中权限
        checkedKeys: [],
        // 角色未修改前权限
        checkedKeys_O: [],
        selectedKeys: [],
        // 权限树数据
        treeData: [],
        // 展开节点
        expandedKeys: [],
        autoExpandParent: true,
        allData: [],
        // 当前登录用户所有角色
        userBindedRoleIdList: [],
        dataPagination:{
            pageSize:14,
            size:'small',
            total: 0,
            showTotal: (total, range) => {
                return i18n.t('menuItem.total')+` ${total} `+i18n.t('menuItem.term')
            },
        }
    },
    mutations: {
        setDataPagination(state, val) {
            state.dataPagination = val;
        },
        // 查询权限Tree
        queryMenu(state) {
            let codeInTrx = {
                trxId: "sysPermission",
                actionFlg: "Q",
            };
            state.loadTree = true
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    state.allData = [...outTrx.oaryA];
                    state.treeData = [];
                    let treeData = [];
                    let list = outTrx.oaryA;
                    for (let i = (list.length - 1); i >= 0; i--) {
                        if (list[i] && list[i].parentId == '-1') {
                            treeData.push({
                                title: list[i].permissionName,
                                key: list[i].id,
                                value: list[i].id,
                                children: [],
                            });
                            list.splice(i, 1);
                        }
                    }
                    treeData.map(item => {
                        js3200.mutations.setTreeData(state, {item, list})
                    })
                    state.treeData = treeData;
                }
            }).finally(() => {
                state.loadTree = false
            });
        },
        setTreeData(state, obj) {
            if (obj.list.length) {
                for (let i = obj.list.length - 1; i >= 0; i--) {
                    if (obj.item.key == obj.list[i].parentId) {
                        obj.item.isLeaf = false;
                        obj.item.children.push({
                            title: obj.list[i].permissionName,
                            key: obj.list[i].id,
                            value: obj.list[i].id,
                            isLeaf: true,
                            children: [],
                        });
                        obj.list.splice(i, 1);
                    }
                }
                for (let j = 0; j < obj.item.children.length; j++) {
                    let item = obj.item.children[j]
                    let list = obj.list
                    js3200.mutations.setTreeData(state, {item, list})
                }
            }
        },
        // 设置展开节点
        setExpandedKeys(state, val) {
            state.expandedKeys = val;
            state.autoExpandParent = false;
        },
        // 设置选中节点
        setCheckedKeys(state, val) {
            state.checkedKeys = val;
        },
        setSelectedKeys(state, val) {
            state.selectedKeys = val;
        },
        // 查询角色已绑定权限接口
        queryCheckAssign(state, val) {
            let codeInTrx = {
                trxId: "sysRole",
                actionFlg: "QB",
                id: val.id
            };
            state.checkedKeys = [],
                state.checkedKeys_O = [],
                SendMsg.sendPostTrx(codeInTrx).then((res) => {
                    let outTrx = res.data;
                    if ('0000000' === outTrx.rtnCode) {
                        state.checkedKeys = outTrx.oaryB.map((item) => {
                            return item.permissionId;
                        });
                        state.checkedKeys_O = state.checkedKeys
                    }
                }).finally(() => {
                });
        },
        // 新增按钮
        addData(state) {
            state.isFlag = 'ADD'
            js3200.mutations.cleanForm(state)
            state.capvisible = true
        },
        // 新增/编辑接口
        addAndUpdate(state, val) {
            let codeInTrx = {}
            let msg = ""
            if (val === 'EDIT') {
                msg = "Update Success!"
                codeInTrx = {
                    trxId: "sysRole",
                    actionFlg: "U",
                    saveOrUpdate: 'update',
                    id: state.selectRow.id,
                    roleName: state.capForm.name,
                    roleDesc: state.capForm.desc,
                };
            } else if (val === 'ADD') {
                msg = "Add Success!"
                codeInTrx = {
                    trxId: "sysRole",
                    actionFlg: "U",
                    saveOrUpdate: 'save',
                    roleName: state.capForm.name,
                    roleDesc: state.capForm.desc,
                };
            }
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    js3200.mutations.queryRole(state)
                    js3200.mutations.cleanForm(state)
                    message.success(msg)
                }
            }).finally(() => {
            });
        },
        // 查询Table
        queryRole(state) {
            let codeInTrx = {
                trxId: "sysRole",
                actionFlg: "Q",
            };
            state.dataSource = []
            state.loadTable = true
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    state.dataSource = outTrx.oaryA.map((item, index) => {
                        item.key = (index + 1);
                        return item;
                    });
                    state.dataPagination.total = outTrx.tblCnt;
                }
            }).finally(() => {
                state.loadTable = false
            });
        },
        // 查询登录用户角色列表
        queryUserBindedRole(state) {
            let codeInTrx = {
                trxId: "sysRole",
                actionFlg: "QU",
            };
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    state.userBindedRoleIdList = outTrx.roleIdList
                }
            })
        },
        // 点击编辑按钮
        updateData(state, val) {
            state.capForm = {
                name: val.roleName,
                desc: val.roleDesc,
            },
                state.isFlag = 'EDIT'
            state.capvisible = true
        },
        // 删除角色接口
        deleteData(state, val) {
            let codeInTrx = {
                trxId: "sysRole",
                actionFlg: "D",
                id: state.selectRow.id,
            };
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    js3200.mutations.queryRole(state)
                    message.success("Delete Success!")
                    // 如果删除了登录用户绑定角色，更新页面
                    if (state.userBindedRoleIdList.indexOf(state.selectRow.id) != -1) {
                        router.go(0)
                    }
                }
            }).finally(() => {
            });
        },
        // 点击分配权限按钮
        assignPermission(state, val) {
            js3200.mutations.queryMenu(state)
            js3200.mutations.queryCheckAssign(state, val)
            state.controlVisible = true
        },
        //表格行数据
        customRow(state, obj) {
            state.selectRow = {
                id: obj.id,
                roleDesc: obj.roleDesc,
                roleName: obj.roleName,
            }
        },
        // 新增/編輯角色弹窗确认
        caphandleOk(state) {
            js3200.mutations.addAndUpdate(state, state.isFlag)
            state.capvisible = false
        },
        // 新增/編輯角色弹窗取消
        caphandleCancel(state) {
            state.capvisible = false
            js3200.mutations.cleanForm(state)
        },
        // 清空弹窗数据
        cleanForm(state) {
            state.capForm = {
                name: '',
                desc: '',
            }
        },
        // 分配权限弹窗确认
        controTreelOk(state) {
            // 获取需要新增和删除的权限id
            const permissionIdsForAdd = state.checkedKeys.filter(id => state.checkedKeys_O.indexOf(id) === -1)
            const permissionIdsForDel = state.checkedKeys_O.filter(id => state.checkedKeys.indexOf(id) === -1)
            if (permissionIdsForAdd.length == 0 && permissionIdsForDel.length == 0) {
                state.controlVisible = false
                return;
            }

            let codeInTrx = {
                trxId: "sysRole",
                actionFlg: "A",
                permissionIdsForAdd,
                permissionIdsForDel,
                id: state.selectRow.id,
                roleName: state.selectRow.roleName,
                roleDesc: state.selectRow.roleDesc,
            };
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                let outTrx = res.data;
                //   console.log(outTrx,'查询分配权限数据')
                if ('0000000' === outTrx.rtnCode) {
                    js3200.mutations.queryRole(state)
                    state.checkedKeys = []
                    state.checkedKeys_O = []
                    state.controlVisible = false
                    message.success("Assign Perssion Success!")

                    // 如果修改了当前用户绑定角色的权限，更新页面
                    if (state.userBindedRoleIdList.indexOf(state.selectRow.id) != -1) {
                        router.go(0)
                    }
                }
            }).finally(() => {
            });
        },
        // 分配权限弹窗取消
        controlTreeCancel(state) {
            state.controlVisible = false
            state.checkedKeys = []
            state.checkedKeys_O = []
        },
    },
    getters: {},
    action: {}
}
export default js3200;
